<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input placeholder="请输入内容" clearable ref="searchInput"
                    v-model="queryInfo.query" :disabled="searchProhibit"
                    @keyup.enter.native="handleSearch"
                    @clear="handleSearch">
            <el-button slot="append" icon="el-icon-search" :disabled="searchProhibit" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="deleteUsers" :loading="deleteUsersProhibit">批量删除</el-button>
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.7)"
        row-key="id" @selection-change="handleSelectionChange" ref="userListRef" :data="userlist"
        style="width: 100%" border stripe>
        <el-table-column type="selection">
        </el-table-column>
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="手机">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch :disabled="scope.row.prohibit" v-model="scope.row.mg_state"
                       @change="changeStatus(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间">
        </el-table-column>
        <el-table-column label="操作" width="175">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)"></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete"
                       @click="showDeleteUserMessageBox(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button size="mini" type="warning" icon="el-icon-setting"
                         @click="showSetUserRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,5,10,20,50]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 新增用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      @closed="resetFields('addUserFormRef')"
      width="50%">
      <el-form :model="addUserForm" ref="addUserFormRef" :rules="addUserFormRules" label-width="80px">
        <el-form-item prop="username" label="账号">
          <el-input v-model="addUserForm.username" clearable placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="addUserForm.password" clearable placeholder="请输入密码" type="password"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="addUserForm.email" clearable placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机">
          <el-input v-model="addUserForm.mobile" clearable placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button :loading="addUserProhibit" type="primary"
                     @click="addUser('addUserFormRef')">确定</el-button>
        </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      @closed="resetFields('updateUserFormRef')"
      width="50%">
      <el-form :model="editUserForm" ref="updateUserFormRef" :rules="editUserFormRules" label-width="80px">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="editUserForm.email" clearable placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号">
          <el-input v-model="editUserForm.mobile" clearable placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser('updateUserFormRef')"
                     :loading="editUserProhibit">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setUserRoleDialogVisible"
      @close="closeUserRoleDialog"
      width="50%">
      <div>
        <p>姓名: {{ this.currentUser.username }}</p>
        <p>角色: {{ this.currentUser.role_name }}</p>
      </div>
      <el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option
          v-for="item in roles"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setUserRoleDialogVisible = false">取 消</el-button>
        <el-button :loading="editUserRoleProhibit" type="primary" @click="editUserRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import common from '@/assets/js/common'

export default {
  data () {
    return {
      prohibitTimeout: 300,
      loading: false,
      searchProhibit: false,
      addUserProhibit: false,
      deleteUsersProhibit: false,
      editUserProhibit: false,
      editUserRoleProhibit: false,
      // 分页查询参数
      queryInfo: {
        query: null,
        pagenum: 1,
        pagesize: 10
      },
      // 用户列表数据
      userlist: [],
      // 总数据量
      total: 0,
      // 新增用户对话框是否显示
      addDialogVisible: false,
      // 新增用户表单
      addUserForm: {
        username: null,
        password: null,
        email: null,
        mobile: null
      },
      // 新增用户表单校验规则
      addUserFormRules: {
        username: this.config.rules.usernameRules,
        password: this.config.rules.passwordRules,
        email: this.config.rules.emailRules,
        mobile: this.config.rules.mobileRules
      },
      // 编辑用户对话框是否显示
      editDialogVisible: false,
      // 编辑用户表单数据
      editUserForm: {
        id: null,
        username: null,
        email: null,
        mobile: null
      },
      // 编辑用户表单校验规则
      editUserFormRules: {
        email: this.config.rules.emailRules,
        mobile: this.config.rules.mobileRules
      },
      // 分配角色对话框是否显示
      setUserRoleDialogVisible: false,
      // 当前用户
      currentUser: {},
      // 分配角色中选中的角色
      selectedRoleId: null,
      // 分配角色中，所有的角色
      roles: [],
      userListSelection: []
    }
  },
  // 页面渲染后，获取用户列表，渲染数据
  created () {
    this.getUserList()
  },
  methods: {
    // 重置表单数据
    resetFields (formName) {
      this.$refs[formName].resetFields()
    },
    // 改变页面大小
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 改变当前页码
    handleCurrentChange (current) {
      this.queryInfo.pagenum = current
      this.getUserList()
    },
    // 刷新用户列表
    async getUserList () {
      this.loading = true
      await common.preventDuplicateSubmit(prohibit => {
        this.searchProhibit = prohibit
      }, async () => {
        const { data: res } = await this.http.get('users', { params: this.queryInfo })
        if (this.failed(res, 200)) return
        // 设置是否禁用修改状态按钮，限流，用于防重提交
        res.data.users.forEach(val => {
          val.prohibit = false
        })
        this.userlist = res.data.users
        this.total = res.data.total
      }, this.prohibitTimeout)
      this.loading = false
    },
    // 搜索框搜索
    async handleSearch () {
      await this.getUserList()
      window.setTimeout(() => {
        this.$refs.searchInput.focus()
      }, this.prohibitTimeout + 30)
    },
    // 修改用户状态
    async changeStatus (row) {
      // 防重提交，限流
      row.prohibit = true
      try {
        const { data: res } = await this.http.put(`users/${row.id}/state/${row.mg_state}`, {})
        if (res.meta.status !== 200) {
          row.mg_state = !row.mg_state
          return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
        }
        return this.$message.success(`${res.meta.status} ${res.meta.msg}`)
      } finally {
        window.setTimeout(() => {
          row.prohibit = false
        }, 1000)
      }
    },
    // 新增用户
    async addUser (formName) {
      this.$refs[formName].validate(async valid => {
        // 如果表单数据校验未通过，则弹出错误提示后返回。
        if (!valid) {
          return this.$message.error('请正确填写表单')
        }
        await common.preventDuplicateSubmit(prohibit => {
          this.addUserProhibit = prohibit
        }, async () => {
          // 表单校验

          // 调用接口，新增用户
          const { data: res } = await this.http.post('users', this.addUserForm)
          // 如果响应结果失败，则弹出错误提示
          if (res.meta.status !== 201) return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
          // 新增用户对话框是否显示，设置为false
          this.addDialogVisible = false
          // 重置表单数据
          this.resetFields(formName)
          // 弹出操作成功对话框
          this.$message.success(`${res.meta.status} ${res.meta.msg}`)
          // 刷新用户列表
          await this.getUserList()
        })
      })
    },
    // 显示修改用户对话框
    async showEditDialog (row) {
      // 调用接口获取用户数据
      const { data: res } = await this.http.get(`users/${row.id}`)
      // 如果接口响应失败，弹出错误提示
      if (res.meta.status !== 200) return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
      // 设置修改用户表单数据
      this.editUserForm = res.data
      // 将修改用户对话框显示状态修改为true
      this.editDialogVisible = true
    },
    // 修改用户
    editUser (formName) {
      this.$refs[formName].validate(async (valid) => {
        await common.preventDuplicateSubmit(prohibit => {
          this.editUserProhibit = prohibit
        }, async () => {
          // 如果参数校验未通过，则提示错误信息
          if (!valid) {
            return this.$message.error('请正确填写表单')
          }
          // 调用接口修改用户信息
          const { data: res } = await this.http.put(`users/${this.editUserForm.id}`, {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile
          })
          // 如果接口响应失败，则弹出异常信息
          if (res.meta.status !== 200) return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
          // 修改用户对话框显示状态设置为 false
          this.editDialogVisible = false
          // 重置修改用户表单数据
          this.resetFields(formName)
          // 弹窗提示操作成功
          this.$message.success(`${res.meta.status} ${res.meta.msg}`)
          await this.getUserList()
        })
      })
    },
    // 显示删除用户对话框
    async showDeleteUserMessageBox (id) {
      const res = await this.$confirm('此操作将永久删除用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'cancel') return
      await this.deleteUser(id)
    },
    // 删除用户
    async deleteUser (id) {
      const { data: res } = await this.http.delete(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
      this.$message.success(`${res.meta.status} ${res.meta.msg}`)
      await this.getUserList()
    },
    // 显示分配角色对话框
    async showSetUserRoleDialog (user) {
      this.currentUser = user
      const { data: res } = await this.http.get('roles')
      this.roles = res.data
      this.setUserRoleDialogVisible = true
    },
    // 关闭分配用户角色对话框
    closeUserRoleDialog () {
      this.selectedRoleId = null
      this.currentUser = {}
      this.setUserRoleDialogVisible = false
    },
    async editUserRole () {
      await common.preventDuplicateSubmit(prohibit => {
        this.editUserRoleProhibit = prohibit
      }, async () => {
        if (!this.selectedRoleId) {
          return this.$message.error('请选择角色')
        }
        const { data: res } = await this.http.put(`users/${this.currentUser.id}/role`, { rid: this.selectedRoleId })
        if (res.meta.status !== 200) return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
        this.$message.success(`${res.meta.status} ${res.meta.msg}`)
        this.setUserRoleDialogVisible = false
        await this.getUserList()
      })
    },
    // 用户列表复选框改变
    handleSelectionChange (val) {
      this.userListSelection = val
    },
    // 批量删除用户
    async deleteUsers () {
      await common.preventDuplicateSubmit(prohibit => {
        this.deleteUsersProhibit = prohibit
      }, async () => {
        if (this.userListSelection.length === 0) {
          this.$message.error('请选择要删除的用户')
        }
        while (this.userListSelection.length !== 0) {
          const user = this.userListSelection.shift()
          const { data: res } = await this.http.delete(`users/${user.id}`)
          if (res.meta.status !== 200) return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
          this.$refs.userListRef.toggleRowSelection(user)
        }
        this.$message.success('删除成功')
      })
      await this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>

</style>
